package cn.tjad.tjad2.module.common.pictureselect;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.GridView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qiandian.android.base.common.bean.CommonListBean;
import com.qiandian.android.base.net.http.HttpConstants;
import com.qiandian.android.base.net.http.IDataCallBack;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.business.RemoteDataService;
import cn.tjad.tjad2.listener.IImageToStringCallback;
import cn.tjad.tjad2.utils.Tools;

/**
 * Created by yanghongbing on 17/12/16.
 */

public class PictureSelectWidget extends FrameLayout implements IDataCallBack {

    @BindView(R.id.image_display_gridview)
    GridView pictureGridView;

    private ImageDisplayAdapter imageDisplayAdapter;

    private final List<LocalMedia> selectedImageList = new ArrayList<>();
    private Fragment fragmentContainer;

    private IPictureUploadCallback pictureUploadCallback;

    private ImagePreviewWindow imagePreviewWindow;

    public PictureSelectWidget(@NonNull Context context) {
        super(context);
        init();
    }

    public PictureSelectWidget(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public void setFragmentContainer(Fragment fragment) {
        this.fragmentContainer = fragment;
    }

    private void init() {
        inflate(getContext(), R.layout.picture_select_view, this);
        ButterKnife.bind(this);
        imageDisplayAdapter = new ImageDisplayAdapter(getContext(), selectedImageList);
        imageDisplayAdapter.setOnAddImageClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isEnabled()) {
                    return;
                }
                PictureSelector pictureSelector;
                if (fragmentContainer != null) {
                    pictureSelector = PictureSelector.create(fragmentContainer);
                } else {
                    pictureSelector = PictureSelector.create((Activity) getContext());
                }
                pictureSelector.openGallery(PictureMimeType.ofImage())
                        .maxSelectNum(5)
                        .minSelectNum(1)
                        .imageSpanCount(4)
                        .selectionMode(PictureConfig.MULTIPLE)
                        .previewImage(true)
                        .isCamera(true)
                        .isZoomAnim(true)
                        .enableCrop(false)
                        .compress(false)
                        .withAspectRatio(1, 1)
//                        .glideOverride(160, 160)
                        .hideBottomControls(false)
                        .isGif(false)
                        .selectionMedia(selectedImageList)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }
        });
        imageDisplayAdapter.setOnDeleteClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = (int) v.getTag();
                selectedImageList.remove(position);
                imageDisplayAdapter.notifyDataSetChanged();
            }
        });
        imageDisplayAdapter.setOnImageClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = (int) v.getTag(R.id.imageview_position);
                if (imagePreviewWindow == null) {
                    imagePreviewWindow = new ImagePreviewWindow(v.getContext());
                }
                imagePreviewWindow.setImageUrlList(getSelectedUrlList());
                imagePreviewWindow.show(position);
            }
        });
        pictureGridView.setAdapter(imageDisplayAdapter);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK && requestCode == PictureConfig.CHOOSE_REQUEST) {
            List<LocalMedia> localMediaList = PictureSelector.obtainMultipleResult(data);
            selectedImageList.clear();
            selectedImageList.addAll(localMediaList);
            imageDisplayAdapter.notifyDataSetChanged();
        }
    }

    public void clear() {
        selectedImageList.clear();
        imageDisplayAdapter.notifyDataSetChanged();
    }

    public void setPictureUploadCallback(IPictureUploadCallback callback) {
        this.pictureUploadCallback = callback;
    }

    public List<LocalMedia> getSelectedImageList() {
        return selectedImageList;
    }

    public void uploadPictures(IPictureUploadCallback callback) {
        this.pictureUploadCallback = callback;
        if (selectedImageList.size() > 0) {
            List<String> imagePath = new ArrayList<>();
            for (LocalMedia media : selectedImageList) {
                imagePath.add(media.getPath());
            }
            Tools.asnycImageToBase64(imagePath, new IImageToStringCallback() {
                @Override
                public void onProgress(int index) {
                }

                @Override
                public void onFinish(List<String> imageDataList) {
                    RemoteDataService.uploadImage(imageDataList, PictureSelectWidget.this);
                }
            });
        } else {
            if (pictureUploadCallback != null) {
                pictureUploadCallback.onSuccess(null);
            }
        }
    }

    @Override
    public boolean onReceiveError(int httpId, int errorCode, String errorMsg) {
        if (pictureUploadCallback != null) {
            pictureUploadCallback.onError(errorMsg);
        }
        return true;
    }

    @Override
    public void onDataRefresh(int httpId, Object responseBean) {
        CommonListBean<String> bean = (CommonListBean<String>) responseBean;
        if (bean.resCode == HttpConstants.CODE_SUCCESS) {
            if (pictureUploadCallback != null) {
                pictureUploadCallback.onSuccess(bean.result);
            }
        }
    }

    private List<String> getSelectedUrlList() {
        List<String> urlList = new ArrayList<>();
        if (selectedImageList.size() > 0) {
            for (LocalMedia localMedia : selectedImageList) {
                String path = "";
                if (localMedia.isCompressed()) {
                    path = localMedia.getCompressPath();
                } else if (localMedia.isCut()) {
                    path = localMedia.getCutPath();
                } else {
                    path = localMedia.getPath();
                }
                urlList.add(path);
            }
        }
        return urlList;
    }

    public interface IPictureUploadCallback {
        void onError(String errorMsg);
        void onSuccess(List<String> urlList);
    }
}
